package model

import (
	"github.com/pkg/errors"
	"time"
)

type Host struct {
	Model          `xorm:"extends"`
	HostName       string     `json:"host_name" xorm:"varchar(50) notnull"`
	Remark         string     `json:"remark" xorm:"text notnull"`
	OnlineStatus   int        `json:"online_status" xorm:"tinyint(1) default(0) notnull"`
	LastOnlineTime *time.Time `json:"last_online_time" xorm:"datetime null"`
	Keys           string     `json:"keys" xorm:"varchar(100) notnull"`
}

var _ DBOperations = &Host{}

func (host *Host) Insert() (int64, error) {
	return DB.Insert(host)
}

func (host *Host) Update() (int64, error) {
	if host.ID == 0 {
		return 0, errors.New("id 为空！")
	}
	return DB.ID(host.ID).MustCols("host_name", "remark", "online_status", "last_online_time").Update(host)
}

func (host *Host) Delete() (int64, error) {
	if host.ID == 0 {
		return 0, errors.New("id 为空！")
	}
	return DB.ID(host.ID).Delete(host)
}

func GetHostByID(id uint) (*Host, error) {
	host := new(Host)
	has, err := DB.ID(id).Get(host)
	if err != nil {
		return nil, err
	}
	if !has {
		return nil, nil
	}
	return host, nil
}

func GetHostByKeys(keys string) (*Host, error) {
	host := new(Host)
	has, err := DB.Where("`keys` = ?", keys).Get(host)
	if err != nil {
		return nil, err
	}
	if !has {
		return nil, nil
	}
	return host, nil
}
